﻿using GMS.NET.Core.Entitys.System;
using GMS.NET.SqlSugarCore.DbCore;
using Microsoft.Data.SqlClient;

namespace GMS.NET.AutoTask.TaskList
{
    [JobDetail("custscheckdeltask", "客户检测删除任务"),
    Cron(TaskCronConst.EveryOne12, CronStringFormat.WithSeconds, RunOnStart = true)]
    public class CustsCheckDelTask : DbManger,IJob
    {
        /// <summary>
        /// 消息队列
        /// 任务非常多时可以使用保证任务执行的稳定性
        /// </summary>
        private readonly ITaskQueue _taskQueue;
        public CustsCheckDelTask(ITaskQueue taskQueue)
        {
            _taskQueue = taskQueue;
        }

        public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
        {
            ///异步队列
            await _taskQueue.EnqueueAsync(async (provider, token) =>
            {
                var custs = await MasterDb.Queryable<GMSNet_Customer>().ToListAsync();
                foreach (var cust in custs) 
                {
                    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(cust.Cust_Connection);

                    if (cust.Cust_Deltime is not null && cust.Cust_Deltime != DateTime.MinValue)
                    {
                        if ((DateTime.Now - cust.Cust_Deltime).Value.TotalHours > 24*3)
                        {
                            await MasterDb.Ado.ExecuteCommandAsync($"DROP DATABASE {builder.InitialCatalog};");
                        }
                    }
                }
            });
        }
    }
}
